<template>
  <!--自定义查询区域-->
  <div class="jeecg-basic-table jeecg-basic-table-form-container">
    <a-form @keyup.enter.native="searchQuery">
      <a-row :gutter="8" type="flex">
        <a-col flex="129px">
          <a-form-item label="部门" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 18 }">
            <JDictSelectTag
              v-model:value="queryParam.ddlxIds"
              mode="multiple"
              dictCode="ddlxType@ddlxUser"
              placeholder="全部"
              :maxTagCount="0"
              :getPopupContainer="(node) => node.parentNode"
              :dropdownStyle="{ width: '150px', overflow: 'auto' }"
              :dropdownMatchSelectWidth="false"
            />
          </a-form-item>
        </a-col>

        <a-col flex="122px">
          <a-form-item label="状态" :label-col="{ style: { width: '40px' } }" >
            <JDictSelectTag
              v-model:value="queryParam.orderStatus"
              dictCode="orderStatus"
              placeholder="全部"
              :maxTagCount="0"
              :getPopupContainer="(node) => node.parentNode"
              :dropdownStyle="{ width: '150px', overflow: 'auto' }"
              :dropdownMatchSelectWidth="false"
            />
          </a-form-item>
        </a-col>

        <a-col flex="320px">
          <a-form-item label="日期" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ style: { width: '250px' } }">
            <a-date-picker
              v-model:value="queryParam.startDate"
              :disabled-date="disabledStartDate"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 125px"
            /> ~
            <a-date-picker
              v-model:value="queryParam.endDate"
              :disabled-date="disabledEndDate"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 125px"
            />
          </a-form-item>
        </a-col>

        <a-col flex="200px">
          <a-form-item label="名称" :label-col="{ style: { width: '40px' } }" >
            <a-input placeholder="" v-model:value="queryParam.goodsName" ></a-input>
          </a-form-item>
        </a-col>

        <a-col flex="150px">
          <a-form-item label="会员" :label-col="{ style: { width: '40px' } }" >
            <a-input placeholder="" v-model:value="queryParam.buyerName" ></a-input>
          </a-form-item>
        </a-col>

        <a-col flex="auto" style="float:right; width:90px; margin-right: 0px;">
          <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
            <a-button type="primary" @click="searchQuery" preIcon="ant-design:search">查询</a-button>
          </span>
        </a-col>

      </a-row>
    </a-form>
  </div>
  <!-- table区域-begin -->
  <BasicTable @register="registerTable" :onRowClick="handleClick" :onRowDbClick="handleDblclick" :rowClassName="rowClassName" :loading="loading">
    <template #tableTitle>
      <a-button type="primary" preIcon="ant-design:edit-outlined" @click="handleEdit" :disabled="orderOption.modButton">编辑</a-button>
      <PopConfirmButton type="primary" color="warning" title="确定审核？" okText="确定" cancelText="取消" preIcon="ant-design:plus-outlined" @confirm="handleAudit" :disabled="orderOption.dooButton">审核</PopConfirmButton>
      <PopConfirmButton type="primary" color="error" title="确定取消？" okText="确定" cancelText="取消" preIcon="ant-design:delete-twotone" @confirm="handleCancel" >撤消</PopConfirmButton>
      <a-button type="primary" color="error" preIcon="ant-design:project-outlined" @click="handleBusiness" :disabled="orderOption.busButton">业务订单</a-button>
    </template>
  </BasicTable>
  <!-- table区域-end-->

  <OrderModal @register="registerOrdersModal" @success="handleSuccess"></OrderModal>

  <BusinessOrder @register="registerBusinessOrder" ></BusinessOrder>
</template>

<script lang="ts" setup name="orders-index">
import { ref, computed, unref, reactive, toRaw } from "vue";
import { BasicTable, TableAction, ActionItem, BasicColumn, FormSchema } from "/@/components/Table";
import { useModal } from "/@/components/Modal";
import { useListPage } from "/@/hooks/system/useListPage";
import { render } from "/@/utils/common/renderUtils";
import { list, audit, revise } from "/@/views/shop/orders/orders.api";
import { momentSearchQueryDate } from "/@/utils/dateUtil";
import { useMessage } from "/@/hooks/web/useMessage";
import { PopConfirmButton } from '/@/components/Button';

import moment from 'dayjs'
import OrderModal from './OrderModal.vue';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import BusinessOrder from '/@/views/full/business/BusinessOrder.vue';

const $message = useMessage();

const orderOption = reactive<any>({
  modButton: false, //编辑
  dooButton: true,  //审核
  canButton: true,  //回退
  busButton: true,  //业务
});


//定义查询表单，查询条件 -------------------------------------------------------------
const queryParam = reactive<any>({
  ddlxIds: [],
  orderStatus: '',
  startDate : momentSearchQueryDate('sub'),
  endDate: momentSearchQueryDate('add'),
});

//限制查询日期，开始日期不能大于结束日期
function disabledStartDate(startDate) {
  const endDate = queryParam.endDate;
  if (!startDate || !endDate) {
    return false;
  }
  return startDate.valueOf() > moment(endDate).valueOf()
}

function disabledEndDate(endDate) {
  const startDate = queryParam.startDate;
  if (!endDate || !startDate) {
    return false;
  }
  return moment(startDate).valueOf() > endDate.valueOf();
}
//定义查询表单，查询条件  -------------------------------------------------------------


//列表组件 -------------------------------------------------------------
//订单列表 - 状态转译
const statusFmt = ({text}: { text: any }) => {
  if (!text) {
    return
  }

  let color = "default";
  if (text == 'TAKE') {
    color = "green";
  } else if (text == 'AUDIT') {
    color = "red";
  } else if (text == 'CANCEL') {
    color = "cyan"
  } else if (text == 'REPAEL') {
    color = "purple"
  } else if (text == 'FINISH') {
    color = "warning"
  }
  
  return render.renderTag(render.renderDict(text, 'orderStatus'), color)
}

// 订单列表 - 表头
const columns: BasicColumn[] = [
  { dataIndex: "orderStatus", title: "状态", width: 35, align: "center", customRender: statusFmt, },
  { dataIndex: "ddlx", title: "部门", width: 30, align: "center", customRender: ({text}) => render.renderDict(text, 'ddlxType') },
  { dataIndex: "groupName", title: "产品名称", width: 150, align: "left" },
  { dataIndex: "num", title: "人数", width: 25, customRender: ({text, record}) => record.groupNum + "'" + record.groupChildNum},
  { dataIndex: "groupTourDate", title: "出团日期", width: 75, align: "center" },
  { dataIndex: "memberName", title: "预订会员", width: 60, align: "center" },
  { dataIndex: "createTime", title: "预订时间", width: 80, align: "center" },
  { dataIndex: "formatGoodsPrice", title: "原价", width: 45, align: "right", className: 'text-blue-600' },
  { dataIndex: "formatDiscountPrice", title: "优惠", width: 45, align: "right", className: 'text-red-600' },
  { dataIndex: "formatFlowPrice", title: "实付", width: 45, align: "right", className: 'text-green-600' },
]

// 列表页面公共参数、方法
const loading = ref<boolean>(false);
const {prefixCls, tableContext} = useListPage({
  designScope: 'shop-orders-list',
  tableProps: {
    rowKey: '(row) => row.sn',
    api: list,
    columns: columns,
    showIndexColumn: true,    //行号
    clickToRowSelect: true,   //点击选择
    showActionColumn: false,
    useSearchForm: false,
    showSummary: false,
    //summaryFunc: handleSummary,
    beforeFetch: (params) => {Object.assign(params, unref(queryParam))}, 
  },
})

//注册table数据
const [registerTable, {reload, setProps, getRawDataSource, redoHeight}] = tableContext

//新增订单
const [registerOrdersModal, {openModal: openModal}] = useModal();
//列表组件 -------------------------------------------------------------


//列表事件 -------------------------------------------------------------

//单击行选中行
let selectRows = reactive<any>({id: '', businessId: ''});
function handleClick(record) {
  selectRows.id = record.id;
  selectRows.businessId = record.businessId;
  selectRows.status = record.orderStatus;
  refreshOrderButton();
}

//按数据状态，启用禁用界面所有表单属性
function refreshOrderButton() {
  let status = selectRows.status;
  if (status == 'TAKE') {
    //未审
    orderOption.modButton = false; 
    orderOption.dooButton = false;
    orderOption.canButton = false;
    orderOption.busButton = true;
  } else if (status == 'AUDIT') {
    //己审
    orderOption.modButton = false; 
    orderOption.dooButton = true;
    orderOption.canButton = true;
    orderOption.busButton = false;
  } else if (status == 'CANCEL') {
    //取消
    orderOption.modButton = false; 
    orderOption.dooButton = false;
    orderOption.canButton = true;
    orderOption.busButton = true;
  } else if (status == 'REPEAL') {
    //撤销
    orderOption.modButton = false; 
    orderOption.dooButton = false;
    orderOption.canButton = true;
    orderOption.busButton = true;
  }


  // if (selectRows.businessId) {
  //   orderOption.busButton = false;
  // } else {
  //   orderOption.busButton = true;
  // }
}

//双击行
function handleDblclick(record) {
  handleEdit(record);
}

function rowClassName(record, index) {
  return record.id === selectRows.id ? 'row-selected' : '';
}

//审核
async function handleAudit() {
  if (!selectRows.id) {
    $message.createMessage.warning("请选择数据！");
    return false;
  }
  await audit({orderSn: selectRows.id}, handleSuccess)
}

//撤销
async function handleCancel() {
  if (!selectRows.id) {
    $message.createMessage.warning("请选择数据！");
    return false;
  }
  let params = selectRows.id
  await revise( params, handleSuccess)
}

/**
 * 编辑事件
 */
async function handleEdit(record: Recordable) {
  if (!selectRows.id) {
    $message.createMessage.warning("请选择数据！");
    return false;
  }
  Object.assign(record, selectRows)
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true
  });
}

//详细订单
const [registerBusinessOrder, {openModal: openBusinessOrder}] = useModal();

function handleBusiness() {
  let businessId = selectRows.businessId;
  if (!businessId) {
    $message.createMessage.warning("请选择数据！");
    return false;
  }

  openBusinessOrder(true, {id: businessId, buttonAll: false});
}

// 查询
function searchQuery() {
  selectRows.id = ""
  setProps({searchInfo:toRaw(queryParam)});
  reload();
}

function handleSuccess() {
  searchQuery();
  orderOption.modButton = false; //编辑
  orderOption.dooButton = true;  //审核
  orderOption.canButton = true;  //回退
  orderOption.busButton = true;  //业务
}

// 统计
function handleSummary() {
  // const res = getRawDataSource()
  // redoHeight();
  // if (res) {
  //   return getRawDataSource().summary;
  // } else {
  //   return [];
  // }
  return [];
}

//默认执行查询
//searchQuery();

</script>
<style scoped>

</style>
